# -*- coding:utf-8 -*-

## =====================================================================
## Copyright (C) 2007-2011  Jean-Philippe GOLAY
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
## =====================================================================


from Tkinter import *
import Pmw
from tkMessageBox import *

from Persistance import *

class ReferenceGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Références")
		self.balloon=balloon
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Reference-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Reference-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tReferenceGUI\tStart")
		self.makeReference()

	# DEBUT de la gestion du module Reference --------------------------------------------------------------------------------------------------------
	def clearFieldReference(self):
		# Mise a zéro des champs de la fiche ItemFamily
		self.referenceValues[0].set("")
		self.referenceValues[1].set("")

	def selectReference(self, event):
		if self.listReference.get(0)!="":
			result = Reference.select(Reference.q.id==self.idListReference[int(self.listReference.curselection()[0])])
			for row in result:
				self.selectedReference = row
			self.referenceValues[0].set(self.selectedReference.code)
			self.referenceValues[1].set(self.selectedReference.category)
			# activation du bouton supprimer
			self.deleteReferenceBt.config(state=NORMAL)

	def searchReference(self, event=None):
		if self.searchReferenceValue.get() != "":
			self.listReference.delete(0,END)
			self.idListReference = []
			result = Reference.select(Reference.q.category.startswith(self.searchReferenceValue.get().encode("utf-8")), orderBy=Reference.q.category)
			for row in result:
				self.listReference.insert(END, row.category+" - "+row.code)
				self.idListReference.append(row.id)
		else:
			self.listReference.delete(0,END)
			self.idListReference = []
			result = Reference.select(orderBy=Reference.q.category)
			for row in result:
				self.listReference.insert(END, row.category+" - "+row.code)
				self.idListReference.append(row.id)

	def makeReference(self):
		leftFrame = Frame(self)
		# Fiche Reference  (présentation colonne de gauche)
		Label(leftFrame, text=u"Référence").pack(side=TOP, fill=X)
		# Création des champs a renseigner pour un object Reference
		referenceLabels = (u"Code", u"Désignation")
		self.referenceValues = [StringVar(), StringVar()]
		count=0
		for name in referenceLabels:
			f = Frame(leftFrame)
			Label(f, width=12, text=name, anchor=W).pack(side=LEFT)
			Entry(f, textvariable=self.referenceValues[count], width=33).pack(side=LEFT, fill=X)
			f.pack(side=TOP, fill=X)
			count+=1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.saveReferenceBt=Button(s, image=self.imgSave, command=self.createReference)
		self.saveReferenceBt.bind("<Return>", self.createReference)
		self.saveReferenceBt.pack(side=LEFT)
		self.balloon.bind(self.saveReferenceBt, u"Enregistrer")
		self.deleteReferenceBt=Button(s, image=self.imgDelete, command=self.deleteReference, state=DISABLED)
		self.deleteReferenceBt.bind("<Return>", self.deleteReference)
		self.deleteReferenceBt.pack(side=LEFT)
		self.balloon.bind(self.deleteReferenceBt, u"Supprimer")
		s.pack(side=TOP, fill=X)
		Label(leftFrame, text=u"Liste des Références").pack(side=TOP, fill=X)
		self.searchReferenceValue = StringVar()
		self.searchReferenceEt = Entry(leftFrame,  width=43, textvariable=self.searchReferenceValue, relief=GROOVE)
		self.searchReferenceEt.bind("<KeyRelease>", self.searchReference)
		self.searchReferenceEt.pack(side=TOP, fill=X)
		self.balloon.bind(self.searchReferenceEt, u"Saisir les premières lettres d'une Famille d'Articles\npour une recherche plus précise,\nla liste est classée par date de début.")
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listReference = Listbox(s)
		self.listReference.config(yscrollcommand=scrollbar.set, width=40, selectmode=SINGLE, height=10)
		self.listReference.bind("<ButtonRelease-1>",self.selectReference)
		scrollbar.config(command=self.listReference.yview)
		self.listReference.pack(side=TOP, fill=X)
		self.balloon.bind(self.listReference, u"Séléctionner une Famille d'Articlese\npour la visualiser ou la modifier.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		# Initialisation
		self.clearFieldReference()
		self.searchReference()

	def verifyReference(self):
		if self.referenceValues[0].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Code est obligatoire !\nMerci de le compléter.")
			return False
		elif self.referenceValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Déscription est obligatoire !\nMerci de le compléter.")
			return False
		else:
			return True

	def createReference(self, event=None):
		if self.verifyReference():
			if  self.deleteReferenceBt.config()["state"][4] == "normal":
				self.modifyReference()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer %s comme une nouvelle Référence ?\n" % self.referenceValues[1].get()):
					Reference(code=self.referenceValues[0].get().encode("utf-8"),
						category=self.referenceValues[1].get().encode("utf-8"),
						createDate=datetime.datetime.now()
					)
					self.searchReference()
				self.clearFieldReference()

	def modifyReference(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier la Référence %s ?" % self.selectedReference.category):
			self.selectedReference.code=self.referenceValues[0].get().encode("utf-8")
			self.selectedReference.category=self.referenceValues[1].get().encode("utf-8")
			self.searchReference()
		self.deleteReferenceBt.config(state=DISABLED)
		self.clearFieldReference()

	def deleteReference(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer la Référence %s ?\nCette opération est irréversible !" % self.selectedReference.category):
			Reference.delete(self.selectedReference.id)
			self.searchReference()            
		self.deleteReferenceBt.config(state=DISABLED)
		self.clearFieldReference()    
	# FIN de la gestion du module Reference --------------------------------------------------------------------------------------------------------------

class ReferenceListGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Liste des Références")
		self.balloon=balloon
		self.imgNew=PhotoImage(file="img/add_alternative_icon.gif")
		self.field=field
		self.index=index
		self.listObject=listObject
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Reference-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Reference-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tReferenceListGUI\tStart")
		self.makeListReference()

	def selectListReference(self, event):
		if self.listListReference.get(0)!="":
			result = Reference.select(Reference.q.id==self.idListListReference[int(self.listListReference.curselection()[0])])
			for row in result:
				self.listObject[self.index]=row
				self.field.set(row.category+" - "+row .code)
				self.destroy()

	def searchListReference(self, event=None):
		if self.searchListReferenceValue.get() != "":
			self.listListReference.delete(0,END)
			self.idListListReference = []
			result = Reference.select(Reference.q.category.startswith(self.searchListReferenceValue.get().encode("utf-8")), orderBy=Reference.q.category)
			for row in result:
				self.listListReference.insert(END, row.category+" - "+row.code)
				self.idListListReference.append(row.id)
		else:
			self.listListReference.delete(0,END)
			self.idListListReference = []
			result = Reference.select(orderBy=Reference.q.category)
			for row in result:
				self.listListReference.insert(END, row.category+" - "+row.code)
				self.idListListReference.append(row.id)

	def makeListReference(self):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Liste de Références").pack(side=TOP, fill=X)
		self.searchListReferenceValue = StringVar()
		s = Frame(leftFrame) 
		self.searchListReferenceEt = Entry(s,  width=42, textvariable=self.searchListReferenceValue, relief=GROOVE)
		self.searchListReferenceEt.bind("<KeyRelease>", self.searchListReference)
		self.searchListReferenceEt.pack(side=LEFT, fill=X)
		self.balloon.bind(self.searchListReferenceEt, u"Saisir les premières lettres d'une Référence\npour une recherche plus précise,\nla liste est classée par désignation.")
		newReferenceBt=Button(s,  image=self.imgNew, command=self.ctrlReference)
		newReferenceBt.pack(side=RIGHT)
		self.balloon.bind(newReferenceBt, u"Créer une nouvelle Référence")
		s.pack(side=TOP, fill=X)
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listListReference = Listbox(s)
		self.listListReference.config(yscrollcommand=scrollbar.set,width=43, selectmode=SINGLE, height=16)
		self.listListReference.bind("<ButtonRelease-1>",self.selectListReference)
		scrollbar.config(command=self.listListReference.yview)
		self.listListReference.pack()
		self.balloon.bind(self.listListReference, u"Séléctionner une Référence.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack()
		self.searchListReference()

	def ctrlReference(self):
		ReferenceGUI(balloon=self.balloon, log=self.log, path=self.path)